export function loadMore(element: any, callback: any){
    function _loadMore(){
        let clientHeight = element.clientHeight;
        let scrollTop = element.scrollTop;
        let scrollHeight = element.scrollHeight;
        if(clientHeight + scrollTop + 10 >= scrollHeight){
            callback();
        }
    }
    element.addEventListener("scroll", debounce(_loadMore, 300));
}

export function downRefresh(element: HTMLDivElement, callback: Function){
    let startY: number;
    let distance: number;
    let originalTop = element.offsetTop;
    let startTop: number;
    let $timer:any = null;
    element.addEventListener("touchstart", function(event: TouchEvent){
        if($timer){
            clearInterval($timer);
        }
        let touchMove = throttle(_touchMove, 30);
        if(element.scrollTop === 0){
            startTop = element.offsetTop;
            startY = event.touches[0].pageY;
            element.addEventListener("touchmove", touchMove);
            element.addEventListener("touchend", touchEnd);
        }

        function _touchMove(event: TouchEvent){
            let pageY = event.touches[0].pageY;
            if(pageY > startY){
                distance = pageY - startY;
                element.style.top = startTop + distance + "px";
            }else{
                element.removeEventListener("touchmove", touchMove);
                element.removeEventListener("touchend", touchEnd);
            }
        }

        function touchEnd(_event: TouchEvent){
            element.removeEventListener("touchmove", touchMove);
            element.removeEventListener("touchmend", touchEnd);
            if(distance > 30){
                callback();
            }
            $timer = setInterval(() => {
                let currenTop = element.offsetTop;
                if(currenTop - originalTop > 1){
                    element.style.top = currenTop - 1 + "px";
                }else{
                    element.style.top = originalTop + "px";
                }
            }, 13);
        }
    })
}

// 防抖
export function debounce(fn: any, wait:number){
    var timeout:any = null;
    return function(){
        if(timeout !== null){
            clearTimeout(timeout);
        }
        timeout = setTimeout(fn, wait);
    }
}
// 节流
export function throttle(func: any, delay: number){
    var pre = Date.now();
    return function(){
        var context = this;
        var args = arguments;
        var now = Date.now();
        if(now - pre > delay){
            func.apply(context, args);
            pre = Date.now();
        }
    }
}

export const store = {
    set(key: string, val: string){
        sessionStorage.setItem(key, val)
    },
    get(key: string){
        return sessionStorage.getItem(key);
    }
}